package controller

import (
	"fmt"
	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"hytx_manager/models"
	"hytx_manager/pkg/app"
	"hytx_manager/pkg/e"
	"hytx_manager/pkg/setting"
	"net/http"
	"strconv"
	"time"
)

//列表

func GetSpreads(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize)))
	t := com.StrTo(c.Query("type")).MustInt()

	if t == 0 {
		data, paginate := models.GetSpreadResultMemberList(page, limit, c)
		render(c, gin.H{
			"paginate": paginate,
			"data":     data,
		})
	} else {
		data, paginate := models.GetNewSpreadResultEnterpriseList(page, limit, c)
		render(c, gin.H{
			"paginate": paginate,
			"data":     data,
		})
	}

}

// 当个详情
func GetSpreadById(c *gin.Context) {
	appG := app.Gin{c}
	id := com.StrTo(c.Query("id")).MustInt()
	t := com.StrTo(c.Query("type")).MustInt()

	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("id必须大于1！")
	if t == 0 {
		data, err := models.GetSpreadResultMemberById(id)
		if err != nil {
			appG.Response(http.StatusOK, e.ERROR, err)
			return
		}
		appG.ResponseMsg(200, "", data)
		return
	} else {
		data, err := models.GetSpreadResultEnterpriseById(id)
		if err != nil {
			appG.Response(http.StatusOK, e.ERROR, err)
			return
		}
		appG.ResponseMsg(200, "", data)
		return
	}

}

// 删除
func DelSpread(c *gin.Context) {
	appG := app.Gin{c}
	id := com.StrTo(c.Query("id")).MustInt()
	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("id必须大于1！")
	// 退还脉宝
	// msg := "管理员删除违规广告"
	//err1 := models.RefundMaiBao(id, msg)
	//if err1 != nil {
	//	appG.Response(http.StatusOK, e.ERROR, err1)
	//	return
	//}
	err := models.DelSpreadById(id)
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR, err)
		return
	}
	appG.ResponseMsg(200, "删除成功！", "")
	return
}

var spread struct {
	Code             string `json:"code"`
	MaibaoNumSurplus int    `json:"maibao_num_surplus"`
	UserId           int    `json:"user_id"`
	Title            string `json:"title"`
	Status           int    `json:"status"`
}

// 修改
func UpdateSpread(c *gin.Context) {
	valid := validation.Validation{}
	appG := app.Gin{c}
	id := com.StrTo(c.Query("id")).MustInt()
	status := com.StrTo(c.PostForm("status")).MustInt()
	t := com.StrTo(c.PostForm("type")).MustInt()
	remarks := c.PostForm("remarks")
	valid.Min(id, 1, "id").Message("id必须大于1！")

	db := models.DB.Begin()

	// 通过id查找出当前选择的spread
	err := db.Table("spread").Select("code, maibao_num_surplus, user_id, title, status").Where("id=?", id).First(&spread).Error
	if err != nil {
		appG.ResponseMsg(200, "数据不存在！", "")
		return
	}

	if status == 1 && spread.Status == status {
		appG.ResponseMsg(200, "不能重复修改！", "")
		return
	}

	if status == 3 {
		if spread.Status == 3 {
			appG.ResponseMsg(200, "下架不能重复修改！", "")
			return
		}
		// 退还脉宝
		msg := "管理员下架广告"
		if t == 0 {
			err := refundMaiBao(db, id, msg)
			if err != nil {
				db.Rollback()
				appG.Response(http.StatusOK, e.ERROR, err)
				return
			}
		} else {
			err := refundEnterpriseMaiBao(db, id, msg)
			if err != nil {
				db.Rollback()
				appG.Response(http.StatusOK, e.ERROR, err)
				return
			}
		}

	}
	if status == 1 {
		if spread.Status == 1 {
			appG.ResponseMsg(200, "审核不通过不能重复修改！", "")
			return
		}
		msg := "管理员审核不通过广告"
		if t == 0 {
			err := refundMaiBao(db, id, msg)
			if err != nil {
				db.Rollback()
				appG.Response(http.StatusOK, e.ERROR, err)
				return
			}
		} else {
			err := refundEnterpriseMaiBao(db, id, msg)
			if err != nil {
				db.Rollback()
				appG.Response(http.StatusOK, e.ERROR, err)
				return
			}
		}

	}

	// 审核
	err = updateSpreadById(db, id, status, remarks)
	if err != nil {
		db.Rollback()
		appG.Response(http.StatusOK, e.ERROR, err)
		return
	}
	db.Commit()
	appG.ResponseMsg(200, "修改成功！", "")
	return
}

// 退还脉宝
func refundMaiBao(db *gorm.DB, id int, msg string) error {

	var users struct {
		Maibao float32 `json:"maibao"`
	}

	// todo 查找用户脉宝数
	errUser := db.Table("users").Select("maibao").Where("id=?", spread.UserId).First(&users).Error
	if errUser != nil {
		return fmt.Errorf("查找用户脉宝数错误")
	}
	maibao := spread.MaibaoNumSurplus + int(users.Maibao)
	//todo 添加用户脉宝
	userErr := db.Table("users").Where("id=?", spread.UserId).Updates(map[string]interface{}{"maibao": maibao}).Error
	if userErr != nil {
		return fmt.Errorf("添加用户脉宝错误")
	}
	num := strconv.Itoa(spread.MaibaoNumSurplus)
	// todo 添加脉宝退还记录
	maibao_bill := models.MaiBaoBill{
		UserId:    spread.UserId,
		Type:      1,
		Title:     msg + spread.Title + "退还脉宝" + num + "个",
		Amount:    float32(spread.MaibaoNumSurplus),
		Cate:      1,
		CreatedAt: time.Now(),
	}
	maibao_bill_id, maibao_billErr := maibao_bill.Add()
	if maibao_billErr != nil {
		return fmt.Errorf("添加脉宝退还记录错误")
	}
	// todo 还记录详情

	maibao_bill_extend := models.MaiBaoBillExtend{
		UserId:    spread.UserId,
		Type:      2,
		BillId:    maibao_bill_id,
		CreatedAt: time.Now(),
	}
	maibao_bill_extendErr := maibao_bill_extend.Add()
	if maibao_bill_extendErr != nil {
		return fmt.Errorf("还记录详情错误")
	}
	// todo redis 删除w
	err1 := models.DelRedisCodeKey(spread.Code)
	if err1 != nil {
		return fmt.Errorf("删除w错误")
	}
	// 清空脉宝剩余个数
	numErr := delSpreadByCodeMaibaoNumSurplus(db, spread.Code)
	if numErr != nil {
		return fmt.Errorf("清空脉宝剩余个数错误")
	}

	return nil
}

func refundEnterpriseMaiBao(db *gorm.DB, id int, msg string) error {
	var maibao struct {
		Maibao float32 `json:"maibao"`
	}
	// todo 查找企业用户的脉宝数
	errEnterprise := db.Table("enterprise").Select("maibao").Where("id=?", spread.UserId).First(&maibao).Error
	if errEnterprise != nil {
		return fmt.Errorf("查找企业用户脉宝错误")
	}
	enterpriseMaiBao := spread.MaibaoNumSurplus + int(maibao.Maibao)
	//todo 添加企业脉宝
	enterpriseErr := db.Table("enterprise").Where("id=?", spread.UserId).Updates(map[string]interface{}{"maibao": enterpriseMaiBao}).Error
	if enterpriseErr != nil {
		return fmt.Errorf("添加企业用户脉宝错误")
	}
	num := strconv.Itoa(spread.MaibaoNumSurplus)
	// todo 添加企业脉宝退还记录
	data := models.EnterpriseMaiBaoBill{
		EnterpriseId: spread.UserId,
		Type:         1,
		Title:        msg + spread.Title + "退还脉宝" + num + "个",
		Cate:         1,
		IsShare:      0,
		Amount:       float64(spread.MaibaoNumSurplus),
		CreatedAt:    time.Now(),
		UpdatedAt:    time.Now(),
	}
	data.Add()
	// todo redis 删除code
	err1 := models.DelRedisCodeKey(spread.Code)
	if err1 != nil {
		return fmt.Errorf("删除错误")
	}

	// todo 清空脉宝剩余个数
	numErr := delSpreadByCodeMaibaoNumSurplus(db, spread.Code)
	if numErr != nil {
		return fmt.Errorf("清空脉宝剩余个数错误")
	}
	return nil
}

// 审核
func updateSpreadById(db *gorm.DB, id int, status int, remarks string) error {
	//if remarks == "" {
	//	remarks = "审核"
	//}
	err := db.Table("spread").Where("id=?", id).Updates(map[string]interface{}{"status": status, "remarks": remarks, "updated_at": time.Now()}).Error
	if err != nil {
		return fmt.Errorf("审核错误")
	}
	return nil
}

// 通过code 清空剩余个数
func delSpreadByCodeMaibaoNumSurplus(db *gorm.DB, code string) error {
	err := db.Table("spread").Where("code=?", code).Updates(map[string]interface{}{"maibao_num_surplus": 0, "updated_at": time.Now()}).Error
	if err != nil {
		return fmt.Errorf("通过code 清空剩余个数错误")
	}
	return nil
}
